package fengstyle;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@SpringBootApplication
public class RedissonLockApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedissonLockApplication.class, args);
        System.out.println("启动成功");
    }

    @Resource
    private Redisson redisson;

    private int number = 9;

//    @PostConstruct
    public void lockTest(){
        RLock lock = redisson.getLock("test-lock");
        try {
            lock.lock();
            System.out.println("number=" + number);
            if(number > 0){
                Thread.sleep((long) (Math. random() * 10000));
                number--;
                System.out.println("number==" + number);
            }
            lock.unlock();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

    }

    @GetMapping("/testLock")
    public void getLock(){
        ExecutorService service = Executors.newCachedThreadPool();
        int size = 20;
        CountDownLatch latch = new CountDownLatch(size);
        for(int i = 0; i < size; i ++){
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("线程" + Thread.currentThread().getName() + "等待");
                        latch.await();
                        lockTest();
                        latch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }
        while (latch.getCount() > 0){

            latch.countDown();
        }
    }



}
